package com.jian.java;

import com.google.gson.Gson;
import com.jian.pojo.Result;
import com.jian.pojo.Student;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Jiange
 * @create 2021-04-12-21:56
 */
public class RegisterConnect extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        //返回数据的json对象
        Map map = new HashMap();
        //JSON转化的对象
        Gson gson = new Gson();
        resp.setContentType("text/json;charset=utf-8");
        byte[] bytes = req.getInputStream().readAllBytes();

        Result result = gson.fromJson(new String(bytes, "utf-8"), Result.class);
        Object type = result.getUser().get("type");
        Object account = result.getUser().get("account");
        String username = result.getUsername();
        String password = result.getPassword();
        String teacher = result.getTeacher();
        System.out.println(type);

        if("student".equalsIgnoreCase(type.toString())){
            System.out.println(account);
            Student student = new Student(username,password,account.toString(),teacher);
            com.jian.dao.impl.Student student1 = new com.jian.dao.impl.Student();
            int b = student1.register(student);
            if(b == -1){
                map.put("mes","该学生账号存在");
                map.put("status","-1");
                String s = gson.toJson(map);
                resp.getWriter().write(s);
                System.out.println("存在");
            }else if( b == -2){
                map.put("mes","该老师不存在");
                map.put("status","-2");
                String s = gson.toJson(map);
                resp.getWriter().write(s);
            }
            else if( b== -3){
                map.put("mes","该用户名存在");
                map.put("status","-3");
                String s = gson.toJson(map);
                resp.getWriter().write(s);
            }else {
                map.put("mes","成功添加用户");
                map.put("status","1");
                String s = gson.toJson(map);
                resp.getWriter().write(s);
            }
        }
    }
}
